package com.example.permission.myjbm.utils;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import com.example.jbmsuppliers.R;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

/**
 * 图片放大 没有用到  被框架取代了
 * Created by JBMhaier on 2017/1/17.
 */

public class MyDialog extends Dialog{
    private final ImageView img;
    private final int screenHeight,screenWidth;

    public MyDialog(Context context) {
        super(context, R.style.AlertDialogStyle);
        DisplayMetrics outMetrics=new DisplayMetrics();
        WindowManager manager = (WindowManager) context.getSystemService(context.WINDOW_SERVICE);
        manager.getDefaultDisplay().getMetrics(outMetrics);
        screenHeight=outMetrics.heightPixels;
        screenWidth=outMetrics.widthPixels;
        View view = View.inflate(context, R.layout.big_pic, null);
        img = (ImageView) view.findViewById(R.id.big_img);
        setContentView(view);
    }

    public void setBitmap(String  url){
//        Picasso.with(getContext()).load(url)..error(R.mipmap.ic_launcher).into(img);
        Picasso.with(getContext())
                .load(url)
                .placeholder(R.mipmap.ic_launcher)
                .error(R.mipmap.ic_launcher)
                .transform(transformation)
                .into(img);
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyDialog.this.dismiss();
            }
        });
        this.show();
    }

    Transformation transformation = new Transformation() {

        @Override
        public Bitmap transform(Bitmap source) {
            Bitmap result = zoomImg(source, screenWidth, screenHeight);

                    if (result != source) {
                        // Same bitmap is returned if sizes are the same
                        source.recycle();
                    }
              return result;

        }

        @Override
        public String key() {
            return "transformation" + " desiredWidth";
        }
        public  Bitmap zoomImg(Bitmap bm, int newWidth ,int newHeight){
            // 获得图片的宽高
            int width = bm.getWidth();
            int height = bm.getHeight();
            // 计算缩放比例
            float scaleWidth = ((float) newWidth) / width;
            float scaleHeight = ((float) newHeight) / height;
            // 取得想要缩放的matrix参数
            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleWidth);
            // 得到新的图片
            Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
            return newbm;
        }
    };

}
